

#include "stdafx.h"
#include "pf_vector.h"

//#include <values.h>

#include "pf_debug.h"
#include "pf_math.h"
#include "pf_constructionline.h"

/**
 * Constructor for a point with default coordinates.
 */
PF_Vector::PF_Vector() {
    //PF_DEBUG->print("PF_Vector::PF_Vector");
    set(0.0, 0.0, 0.0);
}



/**
 * Constructor for a point with given coordinates.
 */
PF_Vector::PF_Vector(double vx, double vy, double vz) {
    //PF_DEBUG->print("PF_Vector::PF_Vector");
    set(vx, vy, vz);
}


/**
 * Constructor for a point with given coordinates in an array
 * or three doubles.
 */
//PF_Vector::PF_Vector(double v[]) {
//    set(v[0], v[1], v[2]);
//}


/**
 * Constructor for a point with given valid flag.
 *
 * @param valid true: a valid vector with default coordinates is created.
 *              false: an invalid vector is created
 */
PF_Vector::PF_Vector(bool valid) {
    //PF_DEBUG->print("PF_Vector::PF_Vector");
    set(0.0, 0.0, 0.0);
    this->valid = valid;
}


/**
 * Destructor.
 */
PF_Vector::~PF_Vector() {
    //PF_DEBUG->print("PF_Vector::~PF_Vector");
}


/**
 * Sets a new position for the vector.
 */
void PF_Vector::set(double vx, double vy, double vz) {
    x = vx;
    y = vy;
    z = vz;
    valid = true;
}


/**
 * Sets a new position for the vector in polar coordinates.
 */
void PF_Vector::setPolar(double radius, double angle) {
    x = radius * cos(angle);
    y = radius * sin(angle);
    z = 0.0;
    valid = true;
}



/**
 * @return The angle from zero to this vector (in rad).
 */
double PF_Vector::angle() const {
    double ret = 0.0;
    double m = magnitude();

    if (m>1.0e-6) {
		double dp = dotP(*this, PF_Vector(1.0, 0.0));
		PF_DEBUG->print("PF_Vector::angle: dp/m: %f/%f", dp, m);
		if (dp/m>=1.0) {
			ret = 0.0;
		}
		else if (dp/m<-1.0) {
			ret = M_PI;
		}
		else {
        	ret = acos( dp / m);
		}
        if (y<0.0) {
            ret = 2*M_PI - ret;
        }
    }
    return ret;
}



/**
 * @return The angle from this and the given coordinate (in rad).
 */
double PF_Vector::angleTo(const PF_Vector& v) const {
	if (!valid || !v.valid) {
		return 0.0;
	}
	else {
    	return (v-(*this)).angle();
	}
}



/**
 * @return Magnitude (length) of the vector.
 */
double PF_Vector::magnitude() const {
	double ret = 0.0;
    // Note that the z coordinate is also needed for 2d
    //   (due to definition of crossP())
	if (!valid) {
		ret = 0.0;
	}
	else {
		ret = sqrt(PF_Math::pow(x,2) + PF_Math::pow(y,2) + PF_Math::pow(z,2));
	}

	return ret;
}


/** 
 * 
 */
PF_Vector PF_Vector::lerp(const PF_Vector& v, double t) const {
    return PF_Vector(x+(v.x-x)*t, y+(v.y-y)*t);
}


/**
 * @return The distance between this and the given coordinate.
 */
double PF_Vector::distanceTo(const PF_Vector& v) const {
	if (!valid || !v.valid) {
		return LX_DOUBLEMAX;
	}
	else {
    	return (*this-v).magnitude();
	}
}



/**
 * @return true is this vector is within the given range.
 */
bool PF_Vector::isInWindow(const PF_Vector& firstCorner, 
		const PF_Vector& secondCorner) {

	double minX = std::min(firstCorner.x, secondCorner.x);
	double maxX = std::max(firstCorner.x, secondCorner.x);
	double minY = std::min(firstCorner.y, secondCorner.y);
	double maxY = std::max(firstCorner.y, secondCorner.y);

	return (x>=minX && x<=maxX && y>=minY && y<=maxY);
}



/**
 * Moves this vector by the given offset. Equal to the operator +=.
 */
PF_Vector PF_Vector::move(PF_Vector offset) {
    *this+=offset;
    return *this;
}



/**
 * Rotates this vector around 0/0 by the given angle.
 */
PF_Vector PF_Vector::rotate(double ang) {
	PF_DEBUG->print("PF_Vector::rotate: angle: %f", ang);
	
    double r = magnitude();
	
	PF_DEBUG->print("PF_Vector::rotate: r: %f", r);
	
    double a = angle() + ang;
	
	PF_DEBUG->print("PF_Vector::rotate: a: %f", a);

    x = cos(a) * r;
    y = sin(a) * r;

	PF_DEBUG->print("PF_Vector::rotate: x/y: %f/%f", x, y);
	
    return *this;
}


/**
 * Rotates this vector around the given center by the given angle.
 */
PF_Vector PF_Vector::rotate(PF_Vector center, double ang) {
    *this = center + (*this-center).rotate(ang);
    return *this;
}


/**
 * Scales this vector by the given factors with 0/0 as center.
 */
PF_Vector PF_Vector::scale(PF_Vector factor) {
    x *= factor.x;
    y *= factor.y;
    return *this;
}



/**
 * Scales this vector by the given factors with the given center.
 */
PF_Vector PF_Vector::scale(PF_Vector center, PF_Vector factor) {
    *this = center + (*this-center).scale(factor);
    return *this;
}



/**
 * Mirrors this vector at the given axis.
 */
PF_Vector PF_Vector::mirror(PF_Vector axisPoint1, PF_Vector axisPoint2) {
	/*
	PF_ConstructionLine axis(NULL, 
		PF_ConstructionLineData(axisPoint1, axisPoint2));
	
	PF_Vector xp = axis.getNearestPointOnEntity(*this);
	xp = xp - (*this);
	(*this) += (xp*2);
	*/

	double phi1 = axisPoint1.angleTo(*this);
	double phi2 = axisPoint1.angleTo(axisPoint2) - phi1;
	double r1 = axisPoint1.distanceTo(*this);
	double r2 = axisPoint2.distanceTo(*this);

	if (r1<1.0e-6 || r2<1.0e-6) {
		// point touches one axis point
	}
	else {
		setPolar(r1, phi1 + 2*phi2);
		(*this) += axisPoint1;
	}

	return *this;
}



/**
 * Streams the vector components to stdout. e.g.: "1/4/0"
 */
std::ostream& operator << (std::ostream& os, const PF_Vector& v) {
    if(v.valid) {
        os << v.x << "/" << v.y << "/" << v.z;
    } else {
        os << "invalid vector";
    }
    return os;
}



/**
 * binary + operator.
 */
PF_Vector PF_Vector::operator + (const PF_Vector& v) const {
    return PF_Vector(x + v.x, y + v.y, z + v.z);
}



/**
 * binary - operator.
 */
PF_Vector PF_Vector::operator - (const PF_Vector& v) const {
    return PF_Vector(x - v.x, y - v.y, z - v.z);
}


/**
 * binary * operator.
 */
PF_Vector PF_Vector::operator * (double s) const {
    return PF_Vector(x * s, y * s, z * s);
}



/**
 * binary / operator.
 */
PF_Vector PF_Vector::operator / (double s) const {
    return PF_Vector(x / s, y / s, z / s);
}



/**
 * unary - operator.
 */
PF_Vector PF_Vector::operator - () const {
    return PF_Vector(-x, -y, -z);
}



/**
 * Scalarproduct (dot product).
 */
double PF_Vector::dotP(const PF_Vector& v1, const PF_Vector& v2) {
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}



/**
 * += operator. Assert: both vectors must be valid.
 */
void PF_Vector::operator += (const PF_Vector& v) {
    x += v.x;
    y += v.y;
    z += v.z;
}


/**
 * -= operator
 */
void PF_Vector::operator -= (const PF_Vector& v) {
    x -= v.x;
    y -= v.y;
    z -= v.z;
}



/**
 * *= operator
 */
void PF_Vector::operator *= (double s) {
    x *= s;
    y *= s;
    z *= s;
}



/**
 * == operator
 */
bool PF_Vector::operator == (const PF_Vector& v) const {
    return (x==v.x && y==v.y && z==v.z && valid==v.valid);
}



/**
 * @return A vector with the minimum components from the vectors v1 and v2.
 * These might be mixed components from both vectors.
 */
PF_Vector PF_Vector::minimum (const PF_Vector& v1, const PF_Vector& v2) {
    return PF_Vector (std::min(v1.x, v2.x),
                      std::min(v1.y, v2.y),
                      std::min(v1.z, v2.z));
}



/**
 * @return A vector with the maximum values from the vectors v1 and v2
 */
PF_Vector PF_Vector::maximum (const PF_Vector& v1, const PF_Vector& v2) {
    return PF_Vector (std::max(v1.x, v2.x),
                      std::max(v1.y, v2.y),
                      std::max(v1.z, v2.z));
}



/**
 * @return Cross product of two vectors.
 */
PF_Vector PF_Vector::crossP(const PF_Vector& v1, const PF_Vector& v2) {
    return PF_Vector(v1.y*v2.z - v1.z*v2.y,
                     v1.z*v2.x - v1.x*v2.z,
                     v1.x*v2.y - v1.y*v2.x);
}


/**
 * Constructor for no solution.
 */
PF_VectorSolutions::PF_VectorSolutions() : vector(NULL) {
    clean();
}



/**
 * Copy constructor
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_VectorSolutions& s) 
	: vector(NULL) {
	alloc(s.getNumber());
	setTangent(s.isTangent());
	for (int i=0; i<s.getNumber(); ++i) {
		set(i, s.get(i));
	}
}



/**
 * Constructor for num solutions.
 */
PF_VectorSolutions::PF_VectorSolutions(int num) : vector(NULL) {
	alloc(num);
}



/**
 * Constructor for one solution.
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_Vector& v1) {
    num = 1;
    vector = new PF_Vector[num];
    vector[0] = v1;
    tangent = false;
}



/**
 * Constructor for two solutions.
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_Vector& v1,
                                       const PF_Vector& v2) {
    num = 2;
    vector = new PF_Vector[num];
    vector[0] = v1;
    vector[1] = v2;
    tangent = false;
}



/**
 * Constructor for three solutions.
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_Vector& v1,
                                       const PF_Vector& v2,
									   const PF_Vector& v3) {
    num = 3;
    vector = new PF_Vector[num];
    vector[0] = v1;
    vector[1] = v2;
    vector[2] = v3;
    tangent = false;
}


/**
 * Constructor for four solutions.
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_Vector& v1,
                                       const PF_Vector& v2,
                                       const PF_Vector& v3,
                                       const PF_Vector& v4) {
    num = 4;
    vector = new PF_Vector[num];
    vector[0] = v1;
    vector[1] = v2;
    vector[2] = v3;
    vector[3] = v4;
    tangent = false;
}


/**
 * Constructor for four solutions.
 */
PF_VectorSolutions::PF_VectorSolutions(const PF_Vector& v1,
                                       const PF_Vector& v2,
                                       const PF_Vector& v3,
                                       const PF_Vector& v4,
									   const PF_Vector& v5) {
    num = 5;
    vector = new PF_Vector[num];
    vector[0] = v1;
    vector[1] = v2;
    vector[2] = v3;
    vector[3] = v4;
    vector[4] = v5;
    tangent = false;
}



/**
 * Destructor.
 */
PF_VectorSolutions::~PF_VectorSolutions() {
    clean();
}


/**
 * Allocates 'num' vectors.
 */
void PF_VectorSolutions::alloc(int num) {
	clean();
	this->num = num;
    vector = new PF_Vector[num];
	for (int i=0; i<num; ++i)  {
    	vector[i] = PF_Vector(false);
	}
    tangent = false;
}

/**
 * Deletes vector array and resets everything.
 */
void PF_VectorSolutions::clean() {
    if (vector!=NULL) {
        delete[] vector;
    }
    vector = NULL;
    num = 0;
    tangent = false;
}



/**
 * @return vector solution number i or an invalid vector if there
 * are less solutions.
 */
PF_Vector PF_VectorSolutions::get(int i) const {
    if (i<num) {
        return vector[i];
    } else {
        return PF_Vector(false);
    }
}



/**
 * @return Number of solutions available.
 */
int PF_VectorSolutions::getNumber() const {
    return num;
}



/**
 * @retval true There's at least one valid solution.
 * @retval false There's no valid solution.
 */
bool PF_VectorSolutions::hasValid() const {
	for (int i=0; i<num; i++) {
        if (vector[i].valid) {
			return true;
		}
	}

	return false;
}



/**
 * Sets the solution i to the given vector.
 * If i is greater than the current number of solutions available,
 * nothing happens.
 */
void PF_VectorSolutions::set(int i, const PF_Vector& v) {
    if (i<num) {
        vector[i] = v;
    }
}



/**
 * Sets the tangent flag.
 */
void PF_VectorSolutions::setTangent(bool t) {
    tangent = t;
}



/**
 * @return true if at least one of the solutions is a double solution
 * (tangent).
 */
bool PF_VectorSolutions::isTangent() const {
    return tangent;
}



/**
 * Rotates all vectors around the given center by the given angle.
 */
void PF_VectorSolutions::rotate(PF_Vector center, double ang) {
    for (int i=0; i<num; i++) {
        if (vector[i].valid) {
			vector[i].rotate(center, ang);
		}
	}
}


/**
 * Scales all vectors by the given factors with the given center.
 */
void PF_VectorSolutions::scale(PF_Vector center, PF_Vector factor) {
    for (int i=0; i<num; i++) {
        if (vector[i].valid) {
			vector[i].scale(center, factor);
		}
	}
}


/**
 * @return vector solution which is the closest to the given coordinate.
 * dist will contain the distance if it doesn't point to NULL (default).
 */
PF_Vector PF_VectorSolutions::getClosest(const PF_Vector& coord,
        double* dist, int* index) const {
		
    double curDist;
    double minDist = LX_DOUBLEMAX;
    PF_Vector closestPoint(false);

    for (int i=0; i<num; i++) {
        if (vector[i].valid) {
            curDist = coord.distanceTo(vector[i]);

            if (curDist<minDist) {
                closestPoint = vector[i];
                minDist = curDist;
                if (dist!=NULL) {
                    *dist = curDist;
                }
                if (index!=NULL) {
                    *index = i;
                }
            }
        }
    }

    return closestPoint;
}


PF_VectorSolutions PF_VectorSolutions::operator = (const PF_VectorSolutions& s) {
	alloc(s.getNumber());
	setTangent(s.isTangent());
	for (int i=0; i<s.getNumber(); ++i) {
		set(i, s.get(i));
	}

	return *this;
}


std::ostream& operator << (std::ostream& os,
                                  const PF_VectorSolutions& s) {
    for (int i=0; i<s.num; ++i) {
        os << "(" << s.get(i) << ")\n";
    }
    os << " tangent: " << (int)s.isTangent() << "\n";
    return os;
}


